<?php
/**
 * Created by PhpStorm.
 * User: phpzh
 * Date: 2020/5/29
 * Time: 16:44
 */

namespace app\common\lib;

use app\common\lib\Aes;
use think\Cache;


/**
 * Class IAuth
 * @package app\common\lib
 * IAuth相关
 * Class IAuth
 */
class IAuth
{
    /**
     * @param $data
     * @return string
     * 设置密码
     */
    public static function setPassword($data)
    {
        return md5($data . config('app.password_pre_halt'));
    }

    /**
     * 生成每次请求的sign
     * @param array $data
     * @return string
     */
    public static function setSign($data = [])
    {
        //1.按字段排序
        ksort($data);
        //2拼接字符串数据
        $string = http_build_query($data);
        //3.通过aes来加密
        $string = (new Aes())->encrypt($string);
        //4.所有字符转换大写
        $string = strtoupper($string);
        return $string;
    }

    /***
     * 检查sign是否正常
     * @param array $data
     * @return boolean
     */
    public static function checkSignPass($data)
    {
        $str = (new Aes())->decrypt($data['sign']);
        if (empty($str)) {
            return false;
        }
        parse_str($str, $arr);
        if (!is_array($arr) || empty($arr['did']) || $arr['did'] != $data['did']) {
            return false;
        }
        if (!config('app_debug')) {
            if (time() - ceil($arr['time'] / 100) > config(app . app_sign_time)) {
                return false;
            }
            //唯一性判定
            if (Cache::get($data['sign'])) {
                return false;
            }
        }

        return true;
    }
}